package cn.ilikes.tools.nosql.jpa.query;

import java.util.List;

import javax.persistence.Parameter;
import javax.persistence.Query;

import cn.ilikes.tools.nosql.jpa.persistences.contexts.AbstractContext;
import cn.ilikes.tools.nosql.jpa.persistences.contexts.operations.QueryOperation;
import cn.ilikes.tools.nosql.jpa.query.iquerys.JPAQuery;
import cn.ilikes.tools.nosql.jpa.query.iquerys.IQuery.QueryType;

public class SQLQueryImpl extends ABSQLQuery {

	private QueryOperation queryOperation;

	public SQLQueryImpl(JPAQuery jpaQuery, AbstractContext context, SQLQueryType queryType) {
		super(context, queryType);
		QueryOperation queryOperation = new QueryOperation(context, jpaQuery, queryType);
		setQueryOperation(queryOperation);

	}

	private void setQueryOperation(QueryOperation queryOperation) {
		this.queryOperation = queryOperation;
	}

	@Override
	public List getResultList() {
		AbstractContext context = getContext();
		queryOperation.setQueryType(QueryType.List);
		return (List) context.operation(queryOperation);
	}

	@Override
	public Object getSingleResult() {
		AbstractContext context = getContext();
		queryOperation.setProperties(getProperties());
		queryOperation.setQueryType(QueryType.Single);
		return (Object) context.operation(queryOperation);
	}

	@Override
	public Query setParameter(String arg0, Object arg1) {
		Parameter parameter = new SQLParameter(arg0, arg1.getClass());
		queryOperation.getJpaQuery().setParameter(parameter, arg1);
		return this;
	}

	@Override
	public Query setFirstResult(int firstResult) {
		queryOperation.setFirstResult(firstResult);
		return this;
	}

	@Override
	public Query setMaxResults(int maxResults) {
		queryOperation.setMaxResults(maxResults);
		return this;
	}

}
